package zhcms.action;

import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import zhcms.db.*;
import zhcms.db.ConnectionPool.PooledConnection;
import zhcms.framework.*;
import zhcms.tool.GyIpAddr;

public class LoginAction implements Action {

	@Override
	public ActionForward excute(HttpServletRequest request, HttpServletResponse response) {
		return null;
	}
	
	public ActionForward main(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
		} 
		catch (UnsupportedEncodingException e1) 
		{
			
		}
		String adminname=request.getParameter("adminname");
		String adminpws=request.getParameter("adminpws");
		
		String loginIp;
		GyIpAddr ip =new GyIpAddr();
		loginIp=ip.getIpAddr(request);
		
		PooledConnection conn = null;
		ResultSet rs = null;
		String sqlStr1="select `AdminID`,AdminName from gyhy_admin where AdminName='"+adminname+"' and AdminPSW=md5('"+adminpws+"')";
		String sqlUpdate="";
		String sqlLog="";
		boolean isok=false;
		try {
			conn = DBManager.getConnection();
			//插入日志：
			rs = conn.executeQuery(sqlStr1);
			if (rs.next())
			{
				isok=true;
				HttpSession session = request.getSession(); 
				session.setAttribute("adminid", rs.getInt("AdminID")+""); 
				session.setAttribute("adminname", rs.getString("AdminName")); 
				int seconds=1*24*60*60;   
				Cookie cookie = new Cookie("adminname", adminname);
      cookie.setMaxAge(seconds);
      response.addCookie(cookie);
      
      Cookie cookie1 = new Cookie("adminid", rs.getInt("AdminID")+"");
      cookie1.setMaxAge(seconds);
      response.addCookie(cookie1);
      
      sqlLog="insert into gyhy_SystemLog(`user` ,  `password` ,  `loginip` ,  `logresult` ,  `addtime` ) values ('"+adminname+"','"+adminpws+"','"+loginIp+"','正常',now());";
      conn.executeUpdate(sqlLog);
			}
			else
			{
				isok=false;
				sqlLog="insert into gyhy_SystemLog(`user` ,  `password` ,  `loginip` ,  `logresult` ,  `addtime` ) values ('"+adminname+"','"+adminpws+"','"+loginIp+"','非法',now());";
				conn.executeUpdate(sqlLog);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs=null;
     conn.close();
     conn=null;
		}
		
		if(isok==true)
		{
			return new ActionForward("/admin/main1.jsp",3,"登陆成功");
		}
		else
		{
			return new ActionForward("/admin/index.jsp",4,"用户名或密码错误!",-1);
		}
		
	}

}
